import pygame
import time
from pygame.locals import *

class MarqueeText:
    def __init__(self, screen, font, text, color, speed, width):
        self.screen = screen
        self.font = font
        self.text = text
        self.color = color
        self.speed = speed  # 每秒移动的距离（像素）
        self.width = width  # 屏幕宽度
        self.surface = font.render(text, True, color)
        self.rect = self.surface.get_rect()
        self.offset = 0  # 初始偏移量

    def update(self):
        # 移动文字并处理边界条件
        self.offset -= self.speed * (time.time() - self.last_time)  # 计算本次移动的距离
        self.offset %= self.width  # 当文字移动出屏幕后回到另一边
        self.rect.x = self.offset

    def draw(self):
        self.screen.fill((0, 0, 0))
        self.screen.blit(self.surface, self.rect)

    def run_marquee(self):
        self.last_time = time.time()  # 记录上一帧的时间
        while True:
            self.update()
            self.draw()
            pygame.display.update()
            pygame.time.Clock().tick(60)  # 确保每秒60帧的速率

            # clock.tick(60)  # 确保每秒60帧的速率
            
            for event in pygame.event.get():
                if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                    pygame.quit()
                    quit()

def main():
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    font = pygame.font.SysFont(None, 32)
    marquee_text = MarqueeText(screen, font, "Hello, World!", (255, 255, 255), 2, 800)

    marquee_text.run_marquee()

if __name__ == "__main__":
    main()